package com.kalua.list.harvester.errorhandling;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import com.kalua.list.domainmodel.product.Product;
import com.kalua.list.domainmodel.retailer.CrawlBatchInfo;
import com.kalua.list.harvester.parser.ProductParseResult;

public class SimpleFailureHandler implements ProcessingFailureHandler {

	private static final String CRAWL_ERROR_TYPE = "CRAWL";

	private static final String INTERNAL_ERROR_TYPE = "INTERNAL";

	private static final Logger logger = LoggerFactory.getLogger(SimpleFailureHandler.class);
	
	private static final String RETAILER_ID_MDC_KEY = "RETAILER_ID";
	private static final String BATCH_ID_MDC_KEY = "BATCH_ID";
	private static final String ERROR_TYPE_MDC_KEY = "ERROR_TYPE_MDC_KEY"; 
	
	private CrawlBatchInfo batchInfo;
	
	public SimpleFailureHandler(CrawlBatchInfo batchInfo) {		
		this.batchInfo = batchInfo;		
	}
	
	@Override
	public void processCrawlError(ProductParseResult parseResult) {
		setMDCContext(false);
		logger.error("{} | {}->{}", parseResult.getVendorLinkProductId(), 
							parseResult.getFailureDetails().getClass().getSimpleName(),
							parseResult.getFailureDetails().getMessage());
		clearMDCContext();
	}

	@Override
	public void processInternalError(Product product, Exception exce) {
		setMDCContext(true);
		logger.error("{}/{} | {}", product.getId(), product.getRetailerIssuedId(), 
							exce.getMessage());
		clearMDCContext();		
	}
	
	private void setMDCContext(boolean internalError) {
		MDC.put(RETAILER_ID_MDC_KEY, this.batchInfo.getRetailerId().getValue());
		MDC.put(BATCH_ID_MDC_KEY, batchInfo.getId().toString());
		if (internalError)
			MDC.put(ERROR_TYPE_MDC_KEY, INTERNAL_ERROR_TYPE);
		else MDC.put(ERROR_TYPE_MDC_KEY, CRAWL_ERROR_TYPE);
	}
	
	private void clearMDCContext() {
		MDC.remove(RETAILER_ID_MDC_KEY);
		MDC.remove(BATCH_ID_MDC_KEY);
		MDC.remove(ERROR_TYPE_MDC_KEY);
	}	
}
